package net.lastcoder.ifserver.nio;

import net.lastcoder.ifserver.packet.Packet;

import org.apache.mina.core.buffer.IoBuffer;
import org.junit.Test;

import java.util.Arrays;

/**
 * auth: WenYF
 * date: 2017/2/13
 */
public class ParserReadUtil {
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.replaceAll(" ", "");
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    @Test
    public void readData() {
        String data = "AA DD 00 00 00 30 00 B8 23 1A 3E 00 0F 31 32 30 2E 32 34 2E 32 31 35 2E 38 32 2F 30 00 0C 33 30 34 36 32 32 38 33 39 37 2F 31 00 00 00 04 11 10 11 11 F4 BF 5E 5A";
        byte[] bytes = hexStringToBytes(data);
        System.out.println(Arrays.toString(bytes));

        LightPacketParser lightPacketParser = new LightPacketParser();
        IoBuffer buffer = IoBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        lightPacketParser.read(buffer);

        Packet packet = lightPacketParser.getPacket();
        System.out.println(packet.toString());
    }
}
